<template>
    <el-form ref="formRef" :model="model" status-icon :rules="rules" label-width="80px" class="myform">
        <el-form-item label="手机号" prop="phone">
            <el-input :prefix-icon="Cellphone" clearable v-model="model.phone" type="text" placeholder="请输入账号(用户名或手机号)"
                autocomplete="off" />
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
            <el-row>
                <el-col :span="13">
                    <el-input :prefix-icon="Message" clearable v-model="model.captcha" type="text" placeholder="请输入验证码"
                        autocomplete="off" />
                </el-col>
                <el-col :span="10" :offset="1">
                    <el-button v-if="flag" @click="sentCaptcha" :disabled="!disabled" type="warning">发送验证码</el-button>
                    <el-button v-else :disabled="true" type="default">{{ count }}S 后发送</el-button>
                </el-col>
            </el-row>
        </el-form-item>

        <el-form-item class="lastitem">
            <div class="alinks">
                <router-link class="litem " to="/reg">立即注册</router-link>
                <router-link class="litem bg" to="/findpass">找回密码</router-link>
            </div>
        </el-form-item>

        <el-form-item class="lastitem">
            <el-button type="success" block class="btnblock" @click="submitForm(formRef)">提交验证</el-button>
            <el-button type="danger" block class="btnblock" @click="resetForm(formRef)">重置</el-button>
        </el-form-item>
    </el-form>
</template>


<script lang="ts" setup>
import { ref, reactive, onMounted, computed, onUnmounted } from 'vue'
import { Calendar, Search, Lock, User, Cellphone, Message } from '@element-plus/icons-vue'
import { formRefType, userInfoFace } from '../../utils/types';
import type { FormRules } from 'element-plus'
import { reg } from '../../utils/validate';
import { ShowError, ShowSuccess } from '../../utils/message';
import { Http } from '../../api/api';
import { useRoute, useRouter } from 'vue-router';
import { useFormHook } from '../../hooks/useFormHook';

const limit = 180;
const flag = ref<Boolean>(true)
const count = ref<number>(limit)

const router = useRouter()
const route = useRoute()
const model = reactive<userInfoFace>({})
const formRef = ref<formRefType>()
let timer: any = null

const rules = reactive<FormRules>({
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        {
            pattern: reg.phone,
            message: '手机号格式不正确'
        }
    ],
    captcha: [
        { required: true, message: '验证码不能为空', trigger: 'blur' },
        {
            pattern: reg.code,
            message: '请输入4位数字验证码'
        }
    ],
})
const disabled = computed(() => {
    return reg.phone.test(model.phone)
})
const { resetForm } = useFormHook()
const submitForm = (formEl: formRefType) => {
    if (!formEl) return;
    formEl.validate(async (valid: boolean) => {
        if (valid) {
            let res = await Http.chechphone({
                phone: model.phone
            }) as unknown as any;
            if (res.code == 200) {

                Http.captchaVerify(model)
                    .then((result: any) => {
                        if (result.data) {

                            Http.gettoken({
                                username: res.result.username,
                                phone: res.result.phone,
                                password: res.result.password,
                            }).then((data: any) => {
                                console.log(data)
                                if (data.code == 200) {
                                    router.push("/main")
                                    localStorage.setItem("phone", res.result.phone)
                                    localStorage.setItem("account", res.result.username)
                                    sessionStorage.setItem('token', data.token)
                                }
                            })
                        }
                    })
                    .catch(err => {
                        ShowError('验证码有误')
                    })
            }
        } else {
            ShowError('数据信息提交有误')
        }
    })
}

// 发送验证码 
const sentCaptcha = async () => {
    let res = await Http.chechphone({
        phone: model.phone
    }) as unknown as any;
    if (res.code == 200) {
        timeDown()
        let result = await Http.captchaSent({ phone: model.phone }) as unknown as any;
        console.log(result)
        if (result.data) {
            ShowSuccess('验证码发送成功')
        } else {
            ShowError('验证码发送失败')
        }
    }
}
const timeDown = () => {
    flag.value = false;
    count.value--;
    timer = setInterval(() => {
        if (count.value > 0) {
            flag.value = false;
            count.value--;
        } else {
            clearInterval(timer)
            timer = null;
            flag.value = true;
            count.value = limit;
        }
    }, 1000)
}
onMounted(() => {
    if (route.query.phone) {
        model.phone = route.query.phone
    } else {
        model.phone = localStorage.getItem("phone")
    }
})

onUnmounted(() => {
    clearInterval(timer)
    timer = null;
})
</script>